package com.fishery.memo.util;

import com.fishery.memo.entity.Task;
import com.fishery.memo.job.SendMessageJob;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.annotation.Resources;
import java.sql.Time;

/**
 * @author run
 * @since 2021/1/30 15:02
 */
@Component
public class MessageManager {

    @Resource(name = "scheduler")
    private Scheduler scheduler;

    //将任务注册进定时任务列表
    public void registerMessage(Task task) throws Exception{
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("userId",task.getUserId());
        jobDataMap.put("content",task.getTaskContent());
        jobDataMap.put("time",task.getTaskTime());
        //创建定时任务
        JobDetail jobDetail = JobBuilder.newJob(SendMessageJob.class)
                                        .withIdentity("job_" + task.getId(), Scheduler.DEFAULT_GROUP)
                                        .setJobData(jobDataMap)
                                        .build();
        String cronExpression = getCronExpression(task.getTaskTime(),task.getTaskWeekday());

        //创建任务触发器
        Trigger trigger = TriggerBuilder
                            .newTrigger()
                            .withIdentity("trigger_" + task.getId(),Scheduler.DEFAULT_GROUP)
                            .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)
                                            .withMisfireHandlingInstructionDoNothing())
                            .build();

        scheduler.scheduleJob(jobDetail,trigger);
        if (scheduler.isShutdown()){
            scheduler.start();
        }
    }

    public void pauseTask(String taskId) throws Exception{
        JobKey jobKey = JobKey.jobKey("job_" + taskId, Scheduler.DEFAULT_GROUP);
        scheduler.pauseJob(jobKey);
    }

    public void resumeTask(String taskId) throws Exception{
        JobKey jobKey = JobKey.jobKey("job_" + taskId, Scheduler.DEFAULT_GROUP);
        scheduler.resumeJob(jobKey);
    }

    public void removeTask(String taskId) throws Exception{
        JobKey jobKey = JobKey.jobKey("job_" + taskId, Scheduler.DEFAULT_GROUP);
        scheduler.deleteJob(jobKey);
    }

    public String getCronExpression(Time taskTime,Integer taskWeekday){
        StringBuffer cronExpression = new StringBuffer();

        //封装cron表达式
        cronExpression.append(taskTime.getSeconds())
                .append(" ")
                .append(taskTime.getMinutes())
                .append(" ")
                .append(taskTime.getHours())
                .append(" ? * ");
        //如果不指定星期几
        if (taskWeekday.equals(0)){
            cronExpression.append("* *");
        }else {
            cronExpression.append(taskWeekday + (taskWeekday < 7 ? 1 : -6)).append(" *");
        }
        return cronExpression.toString();
    }

}
